<template>
  <el-header class="app-header">
    <div class="header-left">
      <el-icon class="menu-icon" @click="toggleSidebar" v-if="showMenuButton">
        <Menu />
      </el-icon>
      <router-link to="/dashboard" class="logo">
        <span class="logo-text">茶叶溯源系统</span>
      </router-link>
    </div>

    <div class="header-center">
      <el-input
        v-model="searchKeyword"
        placeholder="输入批次ID进行溯源查询"
        class="search-input"
        @keyup.enter="handleSearch"
        v-if="showSearch"
      >
        <template #append>
          <el-button icon="Search" @click="handleSearch" />
        </template>
      </el-input>
    </div>

    <div class="header-right">
      <template v-if="isAuthenticated">
        <!-- 通知 -->
        <el-dropdown class="notification-dropdown">
          <el-badge :value="unreadCount" :hidden="unreadCount === 0">
            <el-button text class="notification-btn">
              <el-icon><Bell /></el-icon>
            </el-button>
          </el-badge>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item disabled v-if="notifications.length === 0">
                暂无通知
              </el-dropdown-item>
              <el-dropdown-item
                v-for="notification in notifications"
                :key="notification.id"
              >
                {{ notification.message }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <!-- 用户菜单 -->
        <el-dropdown class="user-dropdown">
          <div class="user-info">
            <el-avatar :src="user?.profile?.avatar" :size="32">
              <el-icon><User /></el-icon>
            </el-avatar>
            <span class="username">{{ user?.username || user?.email }}</span>
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="goToProfile">
                <el-icon><User /></el-icon>
                个人资料
              </el-dropdown-item>
              <el-dropdown-item @click="goToSettings">
                <el-icon><Setting /></el-icon>
                设置
              </el-dropdown-item>
              <el-dropdown-item divided @click="handleLogout">
                <el-icon><SwitchButton /></el-icon>
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>

      <template v-else>
        <el-button type="primary" @click="goToLogin">登录</el-button>
        <el-button @click="goToRegister">注册</el-button>
      </template>
    </div>
  </el-header>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Menu,
  Search,
  Bell,
  User,
  ArrowDown,
  Setting,
  SwitchButton
} from '@element-plus/icons-vue'

// Props
defineProps({
  showMenuButton: {
    type: Boolean,
    default: false
  },
  showSearch: {
    type: Boolean,
    default: true
  }
})

// Emits
const emit = defineEmits(['toggle-sidebar'])

const router = useRouter()
const authStore = useAuthStore()

// 状态
const searchKeyword = ref('')
const notifications = ref([])
const unreadCount = ref(0)

// 计算属性
const isAuthenticated = computed(() => authStore.isAuthenticated)
const user = computed(() => authStore.user)

// 方法
const toggleSidebar = () => {
  emit('toggle-sidebar')
}

const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    router.push(`/trace/${searchKeyword.value.trim()}`)
    searchKeyword.value = ''
  } else {
    ElMessage.warning('请输入批次ID')
  }
}

const goToProfile = () => {
  router.push('/profile')
}

const goToSettings = () => {
  ElMessage.info('设置功能开发中')
}

const goToLogin = () => {
  router.push('/login')
}

const goToRegister = () => {
  router.push('/register')
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await authStore.logout()
    ElMessage.success('已退出登录')
    router.push('/login')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退出登录失败:', error)
    }
  }
}
</script>

<style scoped>
.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  height: 60px;
}

.header-left {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.menu-icon {
  font-size: 20px;
  margin-right: 16px;
  cursor: pointer;
  color: #606266;
}

.menu-icon:hover {
  color: #409eff;
}

.logo {
  display: flex;
  align-items: center;
  text-decoration: none;
  color: #2c3e50;
  font-weight: 600;
  font-size: 18px;
}

.logo-text {
  margin-left: 8px;
}

.header-center {
  flex: 1;
  display: flex;
  justify-content: center;
  padding: 0 20px;
}

.search-input {
  max-width: 400px;
  width: 100%;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.notification-dropdown,
.user-dropdown {
  cursor: pointer;
}

.notification-btn {
  padding: 8px;
  font-size: 18px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f7fa;
}

.username {
  font-size: 14px;
  color: #2c3e50;
  max-width: 120px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

@media (max-width: 768px) {
  .app-header {
    padding: 0 16px;
  }
  
  .header-center {
    padding: 0 16px;
  }
  
  .search-input {
    max-width: 300px;
  }
  
  .username {
    display: none;
  }
}
</style>